<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
	}

	public function index()
	{
		$this->load->library('session');
		if($this->session->userdata('id'))
		{
			redirect('salaaula/listasalas');
			return;
		}
		
		if(!$this->input->post())
		{
			$this->load->helper(array('url','form'));
			$dados = array('title' => 'Login');
			$this->carrega_view('index',$dados);
			return;
		}

		$regras = array(
				array('field' => 'senha', 'label' => 'Senha', 'rules' => 'required|xss_clean|min_length[7]|max_length[50]'),
				array('field' => 'nome', 'label' => 'Nome', 'rules' => 'required|xss_clean|max_length[100]')
		);

		$this->load->library('form_validation');
		$this->form_validation->set_rules($regras);
		$this->form_validation->set_error_delimiters('<span class="erro">','</span>');

		if($this->form_validation->run() == FALSE)
		{
			$this->load->helper(array('url','form'));
			$dados = array('title' => 'Login');
			$this->carrega_view('index');
			return;
		}

		$this->load->database();
		$this->load->model('Login_Model');
		if($id = $this->Login_Model->Logar())
		{
			$this->db->close();
			$this->session->set_userdata(array('id' => $id));
			redirect('salaaula/listasalas');
			return;
		}

		$this->load->helper(array('url','form'));
		$dados = array('title' => 'Login','erro' => 'E-mail ou senha incorreto.');
		$this->carrega_view('index',$dados);
		return;
	}
	
	private function carrega_view($caminho_view, $dados = ''){
	
		$dados['logado'] = $this->session->userdata('id') ? true : false;
		$this->load->view('templates/cabecalho', $dados);
		$this->load->view($caminho_view, $dados);
		$this->load->view('templates/rodape');
	}

	public function sair()
	{
		$this->load->library('session');
		$this->session->sess_destroy();
		$this->load->helper('form','url');
		$dados = array('title' => 'Login');
		$this->carrega_view('index',$dados);
	}
}